// 说明：为适配鸿蒙 Web 引擎与 Electron 旧版本（如 Electron 11，Node 12），
// 在 Object.hasOwn 不可用或 web 环境下使用轻量 console 日志，避免 @dabh/diagnostics/colorspace 崩溃。
const IS_WEB = process.env.IS_WEB
const NODE_MAJOR = parseInt(((process.versions && process.versions.node) || '0').split('.')[0], 10)
const NEEDS_LEGACY = (typeof Object.hasOwn !== 'function') || (((process.versions && process.versions.electron)) && NODE_MAJOR < 16)

let logger
if (IS_WEB || NEEDS_LEGACY) {
  logger = {
    info: (...args) => console.info('[pomotroid]', ...args),
    error: (...args) => console.error('[pomotroid]', ...args),
    debug: (...args) => console.debug('[pomotroid]', ...args)
  }
} else {
  const electron = require('electron')
  const os = require('os')
  const path = require('path')
  const winston = require('winston')
  require('winston-daily-rotate-file')

  const app = electron.app || electron.remote.app
  app.setAppLogsPath(path.join(app.getPath('userData'), 'logs'))
  const userDataPath = app.getPath('logs')
  const jsonWithTimestamp = winston.format.combine(
    winston.format.timestamp(),
    winston.format.json()
  )

  logger = winston.createLogger({
    defaultMeta: { hostname: os.hostname() },
    format: jsonWithTimestamp,
    transports: [
      new winston.transports.File({
        filename: path.join(userDataPath, 'pomotroid-error.log'),
        level: 'error',
        maxsize: 1000
      }),
      new winston.transports.DailyRotateFile({
        filename: path.join(userDataPath, 'pomotroid-%DATE%.log'),
        maxFiles: '14d',
        maxSize: '20m'
      })
    ]
  })

  if (process.env.NODE_ENV !== 'production') {
    logger.add(new winston.transports.Console({
      format: winston.format.simple(),
      level: 'debug'
    }))
  }
}

export { logger }
